package com.fourhats.dao.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fourhats.dao.VisitEntityDAO;
import com.fourhats.model.VisitEntity;

@Repository
public class VisitEntityDAOImpl extends GenericDAOImpl<VisitEntity, Long> implements VisitEntityDAO {

	protected VisitEntityDAOImpl() {
		super(VisitEntity.class.getName());
	}

	public long getQtyVisits(long entityId, int entityType) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.setProjection(Projections.rowCount());
		
        criteria.add(Restrictions.eq("entityId", entityId));
        criteria.add(Restrictions.eq("entityType", entityType));

        return new Long((Integer) getHibernateTemplate().findByCriteria(criteria).get(0));
	}

	public boolean hasVisitInHour(long entityId, int entityType, long userId, int hour) {
		Date date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.HOUR_OF_DAY, -hour);
		date = cal.getTime();
		
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.createCriteria("user", "user");
		criteria.add(Restrictions.eq("entityId", entityId));
        criteria.add(Restrictions.eq("entityType", entityType));
        criteria.add(Restrictions.eq("user.id", userId));
        criteria.add(Restrictions.gt("date", date));
        
        return getHibernateTemplate().findByCriteria(criteria, 0, 1).size() > 0;
	}

	@SuppressWarnings("unchecked")
	public VisitEntity getLastByUserAndType(long userId, int entityType) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		
        criteria.add(Restrictions.eq("entityId", userId));
        criteria.add(Restrictions.eq("entityType", entityType));

        List<VisitEntity> visitEntities = getHibernateTemplate().findByCriteria(criteria);
        if(!visitEntities.isEmpty()) {
        	return visitEntities.get(visitEntities.size() - 1);
        }

        return null;
	}
}
